package cn.wiseda.finance.dao;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Component;

import cn.wiseda.finance.dao.util.JdbcBasicDao;
import cn.wiseda.finance.entity.Bank;

@Component
public class BankDao extends JdbcBasicDao {

	/**
	 * 查询所有的银行信息
	 * 
	 * @return
	 */
	public List<Bank> queryBanks() {
		String sql = "select * from t_bank";
		List<Bank> list = queryForBeans(sql, Bank.class);
		return list;
	}

	/**
	 * 查询指定机构下的银行信息
	 * 
	 * @param oid
	 *            机构代码
	 * @return
	 */
	public List<Bank> queryBankByOid(int oid) {
		String sql = "select * from t_bank where organ_id = ?";
		List<Bank> list = queryForBeans(sql, Bank.class, oid);
		return list;
	}

	/**
	 * 根据ID查询单个银行信息
	 * 
	 * @param id
	 * @return
	 */
	public Bank getBank(int id) {
		String sql = "select * from t_bank where id=?";
		// BeanPropertyRowMapper<Bank> bprm = new BeanPropertyRowMapper<Bank>(Bank.class);
		// Bank bank = jdbcTemplate.queryForObject(sql, bprm, id);
		Bank bank = queryForBean(sql, Bank.class, id);
		return bank;
	}

	/**
	 * @return
	 */
	public double sumBankRemarks() {
		String sql = "select sum(bank_balance) from t_bank";
		// TODO 当数据表中无数据会报空指针异常！
		double sum = getJdbc().queryForObject(sql, Double.class);
		return sum;

	}

	/**
	 * @return
	 */
	public double sumBankRemarksByOid(int oid) {
		String sql = "select sum(bank_balance) from t_bank where organ_id = ?";
		// TODO 当数据表中无数据会报空指针异常！
		Double sum = getJdbc().queryForObject(sql, Double.class, oid);
		if (sum == null) {
			return 0;
		}
		return sum;

	}

	public boolean createBank(Bank bank) {
		String sql = "insert into t_bank(bank_name,bank_type,bank_code,bank_balance,bank_remarks) values(?,?,?,?,?)";
		int update = getJdbc().update(sql, bank.getBankName(), bank.getBankType(), bank.getBankCode(),
				bank.getBankBalance(), bank.getBankRemarks());
		return update > 0 ? true : false;
	}

	public boolean modifyBank(Bank bank) {
		String sql = "UPDATE t_bank SET bank_name=?,bank_code=?,bank_type=?,bank_balance=?,bank_remarks=?,organ_id=? WHERE id=?";
		int update = getJdbc().update(sql, bank.getBankName(), bank.getBankCode(), bank.getBankType(),
				bank.getBankBalance(), bank.getBankRemarks(), bank.getOrganId(), bank.getId());
		return update > 0 ? true : false;
	}

	public List<Bank> queryBanks(Bank bank) {
		String sql = "select * from t_bank where bank_name like ? and bank_code like ? and bank_type like ?";
		BeanPropertyRowMapper<Bank> bprm = new BeanPropertyRowMapper<Bank>(Bank.class);

		List<Bank> list = getJdbc().query(sql, bprm, bank.getBankName(), bank.getBankCode(), bank.getBankType());

		return list;
	}
}
